<template>
  <div class="update-photo">
    <!--
      裁剪区域一定要进行块元素的包裹 这个是cropperjs使用的前提
      图片的最大宽度也一定是100%
      图片也一定是块元素
     -->
    <img :src="img" class="img" ref="img" />

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
/* 裁剪的js文件 */
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
/* 裁剪的请求 */
import { updateUserPhoto } from '@/api/user'
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {
      cropper: null
    }
  },
  watch: {},
  computed: {},
  methods: {
    onConfirm () {
      // console.log(this.cropper.getData()); 方式一的裁切必须要服务端的支持才可以
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        this.updateUserPhoto(blob)
      }) // 方式2，是属于纯客户端的裁切getCroppedCanvas() 获取裁切的文件的对象
    },
    async updateUserPhoto (blob) {
      this.$toast.loading({
        message: '保存中.......',
        forbidClick: true, // 禁止背景点击
        duration: 0 // 持续展示
      })
      try {
        //  console.log(blob);
        /*
        如果接口要求content-Type,是application/json，则传递普通的js对象
        */
        // updateUserPhoto({
        //   photo:blob
        // })
        /*
        如果接口要求content是multipart/form-data,则你必须要传递formData对象
        */
        const formData = new FormData()
        formData.append('photo', blob)
        const { data } = await updateUserPhoto(formData)
        console.log(data) // 这里返回的是裁切之后的对象
        /* 关闭弹层 */
        this.$emit('close')
        /* 更新视图 */
        this.$emit('update-photo', data.data.photo)
        /* 提示成功 */
        this.$toast('更新成功!')
      } catch (err) {
        this.$toast('更新失败，请稍后重试~')
      }
    }
  },
  created () {},
  mounted () {
    const image = this.$refs.img
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: 'move',
      aspectRatio: 1,
      // autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      background: false
    })
    // console.log(cropper);
  }
}
</script>
<style lang="less" scoped>
.update-photo {
  background-color: #000;
  height: 100%;

  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
  }
  .cancel,
  .confirm {
    width: 90px;
    height: 90px;
    font-size: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
